import { HOST } from './constant'
import { apiUpdateBackgroundDownNumber, getBackgroundNumber, userRegister, submitDownIp } from './api'
import { getImageInfo, wxlogin } from './utils'
export async function startDow({ imgUrl }) {
  wx.showLoading({
    title: '正在下载'
  })
  let _imgUrl = imgUrl
  if (imgUrl.indexOf('http') === -1) {
    _imgUrl = HOST + imgUrl
  }
  const img = await getImageInfo(_imgUrl)
  wx.saveImageToPhotosAlbum({
    filePath: img.path,
    success: () => {
      submitDownIp({ imgid: _imgUrl }) // 下载记录 记录下载人ip和图片地址
      wx.showToast({
        title: '保存成功',
        mask: true
      })
      apiUpdateBackgroundDownNumber({
        userId: wx.getStorageSync('userSignature')
      })
    },
    fail: (err) => {
      wx.hideLoading();
      wx.showModal({
        title: '提示',
        content: '请允许保存图片到相册',
        success: (res) => {
          if (res.confirm) {
            wx.openSetting({
              success: (settingdata) => {
                if(settingdata.authSetting['scope.writePhotosAlbum'] ) {
                  wx.showModal({
                    title: '提示',
                    content: '获取权限成功，请再次保存图片即可',
                    showCancel: false
                  })
                } else {
                  wx.showModal({
                    title: '提示',
                    content: '授权失败',
                    showCancel: false
                  })
                }
              }
            })
            return
          }
        wx.showToast({
          title: '保存失败',
          icon: 'error',
          mask: true
        })
        }
      })

    }
  });
}

export async function dowImg({ imgUrl }) {
  const signature = await wxlogin()
  const option = {
    userId: signature,
    inviter: ''
  }
  const res = await userRegister(option)
  let count = 0;
  if (res.code === 2) { // 新注册
    startDow({ imgUrl })
    return
  }
  if (res.code === 1) { // 已经注册过了
    let [rsdata] = await getBackgroundNumber(option)
    count = rsdata.number
  }
  if (count > 0) {
    startDow({ imgUrl })
  } else {
    wx.showModal({
      title: '提示',
      content: '下载次数用完啦',
      success: (res) => {
        wx.switchTab({ url:'/pages/user/index' })
      }
    })
  }
}